import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateGoodDto, GoodResponseDto } from '../dto/good.dto';

@Injectable()
export class GoodService {
  private goods: GoodResponseDto[] = [];
  private idCounter = 1;

  constructor() {
    // 初始化一些测试数据
    this.create({ name: 'iPhone 15', price: 5999 });
    this.create({ name: 'MacBook Pro', price: 12999 });
  }

  findAll(): GoodResponseDto[] {
    return this.goods;
  }

  findOne(id: number): GoodResponseDto {
    const good = this.goods.find(g => g.id === id);
    if (!good) {
      throw new NotFoundException(`商品 ID ${id} 不存在`);
    }
    return good;
  }

  create(createGoodDto: CreateGoodDto): GoodResponseDto {
    const newGood: GoodResponseDto = {
      id: this.idCounter++,
      name: createGoodDto.name,
      price: createGoodDto.price,
      description: createGoodDto.description,
      createdAt: new Date(),
    };
    this.goods.push(newGood);
    return newGood;
  }
}